package com.example.avmanagerweb.Utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
	
		private static final String ALGORITHM = "AES";
		private static final String CHARSET = "UTF-8";
		private static final String KEY = "JWD-TIWN$#JNGSS9";		 //16, 24, or 32 bytes key
		
		

		
		/**
		 * 实现数据的AES加密
		 * @param content
		 * @param key
		 * @return
		 * @throws Exception
		 */
		public static String encrypt(String content) throws Exception {
			SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(CHARSET), ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] encryptedBytes = cipher.doFinal(content.getBytes(CHARSET));
			return Base64.getEncoder().encodeToString(encryptedBytes);
		}
		
		
		
		
		/**
		 * 实现AES解密
		 * @param content
		 * @param key
		 * @return
		 * @throws Exception
		 */
		public static String decrypt(String content) throws Exception {
				SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(CHARSET), ALGORITHM);
				Cipher cipher = Cipher.getInstance(ALGORITHM);
				cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
				byte[] encryptedBytes = Base64.getDecoder().decode(content);
				byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
				return new String(decryptedBytes, CHARSET);
		}

	/**
	 * 实现AES解密
	 * @param content
	 * @param KEY
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String content,String KEY) throws Exception {
		SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(CHARSET), ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		byte[] encryptedBytes = Base64.getDecoder().decode(content);
		byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
		return new String(decryptedBytes, CHARSET);
	}
		
		
		
}


